package com.newland.zxy;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2021/1/15
 */
public class CuratorTestMain {

    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        final CuratorFramework client = CuratorFrameworkFactory.builder()
            //server地址
            .connectString("127.0.0.1:2181")
            // 会话超时时间
            .sessionTimeoutMs(5000)
            // 连接超时时间
            .connectionTimeoutMs(3000)
            // 重试策略
            .retryPolicy(retryPolicy)
            // ⽴命名空间/base
            .namespace("base")
            .build();
        client.start();
        System.out.println("连接");
        //创建节点
        client.create().creatingParentsIfNeeded().
            withMode(CreateMode.PERSISTENT).forPath("/curator","curator".getBytes());
        //写入数据
        client.setData().forPath("/curator","data".getBytes());
        //获取数据
        byte[] bytes = client.getData().forPath("/curator");
        //删除节点
        //client.delete().forPath("/curator");
        //注册监听
        client.getChildren().usingWatcher(new CuratorWatcher() {
            public void process(WatchedEvent event) throws Exception {
                if(event.getType()== Watcher.Event.EventType.NodeChildrenChanged)
                {
                    System.out.println(event.getPath());
                    System.out.println(client.getChildren().forPath("/curator"));
                    client.getChildren().usingWatcher(this).forPath(event.getPath());
                }
            }
        }).forPath("/curator");

        for(int i=0;i<30;i++)
        {
            client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).
                forPath("/curator/seq",("seq"+i).getBytes());
            Thread.sleep(2000);
        }
    }
}
